/* 
 * File:   BlockGroup.cpp
 * Author: Usama, Max, Andy
 * 
 * Created on February 4, 2011, 10:15 AM
 */

#include "BlockGroup.h"


BlockGroup::BlockGroup(BlockLinkedList 	bll) : BlockLinkedList(&bll){
}

BlockGroup::BlockGroup(int startBlock, int endBlock, int numberOfBlocks, 
        BlockLinkedList *motherFreeList) : 
        BlockLinkedList(motherFreeList->GetDisk(),Disk::DEFAULT_BLOCK_SIZE-4)
{
    if(startBlock <= 0 || endBlock <= 0 || startBlock > endBlock || numberOfBlocks <= 0 ||
            numberOfBlocks > m_disk->numberOfBlocks()) {
        cout << "BlockGroup Error: Failed to re-open BlockGroup" << endl;
        throw new BlockGroupException;
    }
    else{
        m_motherFreeList = motherFreeList;
        m_startBlockNumber = startBlock;
        m_endBlockNumber = endBlock;
        m_numberOfBlocks = numberOfBlocks;
        m_seek = new Block(m_startBlockNumber,m_disk);
    }

}
bool BlockGroup::AddBlock() {
    bool returnValue = true;
    int numFreeBlocks = m_motherFreeList->GetNumberOfBlocks();

    if (numFreeBlocks == 0) {
        cout << "BlockGroup Error: Failed to add a block since there is no "
                "free blocks to add" << endl;
        returnValue = false;
        throw new BlockGroupException;
    }
    else {
        Block *freeBlock = m_motherFreeList->UnlinkBlock();
        if(!BlockLinkedList::AddBlock(freeBlock)) {
            cout << "BlockGroup Error: Failed to add free block to blockgroup" << endl;
            returnValue = false;
            throw new BlockGroupException;
        }
        delete freeBlock;
    }
}

void BlockGroup::SetFreeList(BlockLinkedList* motherFreeList) {
    m_motherFreeList = motherFreeList;
}

BlockGroup::~BlockGroup() {
    delete m_motherFreeList;
}

